package com.liumin.comlink.http.response;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.liumin.publiclib.helper.CrashHandler;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;


/**
 * 请求失败，返回数据格式与正确返回数据格式不一样的处理
 * 2019/12/25 10:21
 *
 * @author LiuWeiHao
 */
public class HttpGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;
    private static final Charset UTF_8 = Charset.forName("UTF-8");

    public HttpGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        System.out.println("response" + value.string());
        //先将返回的json数据解析到Response中，如果code==200，则解析到我们的实体基类中，否则抛异常
//        BaseResponse httpResult = gson.fromJson(response, BaseResponse.class);
//        if (!"200".equals(httpResult.getCode())) {
//            //200的时候就直接解析，不可能出现解析异常。因为我们实体基类中传入的泛型，就是数据成功时候的格式
//            throw new ApiException(Integer.parseInt(httpResult.getCode()), httpResult.getMsg());
//        }
        MediaType contentType = value.contentType();
        Charset charset = contentType != null ? contentType.charset(UTF_8) : UTF_8;
        InputStream inputStream = new ByteArrayInputStream(response.getBytes());
        Reader reader = new InputStreamReader(inputStream, charset);
        JsonReader jsonReader = gson.newJsonReader(reader);
        try {
            return adapter.read(jsonReader);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            CrashHandler.postCatchedException(e);
            throw new NumberFormatException(e.getMessage());
        } finally {
            value.close();
        }
    }
}
